<template>
  <div class="my-page-layout pl_12">
    <div class="my_add flex justify_between align_center vertical_middle cursor_point pr_12"
      @click="handleOpenPageDialog">
      <img src="https://fengnull.gitee.io/picture_house/page/new-project.png" alt="" class="h_100 my_add_img">
      <div class="my_add_text pl_8 fontsize_14">创建页面</div>
    </div>
    <div class="my_header font_bolder px_4 pt_4 pb_4 sticky flex justify_between align_center">
      <div class="my_header_title">
        {{ projectInfo.name }}
      </div>
      <div class="pr_8">
        <el-input size="small" placeholder="搜索" v-model.trim="query.name" @keyup.enter.native="getPageList" clearable
          @change="getPageList"></el-input>
      </div>
    </div>
    <div class="page_list flex flex_wrap justify_start align_center" v-loading="pageLoading"
      :element-loading-spinner="loadingSvg" element-loading-text="加载中..."
      element-loading-background="rgba(0, 0, 0, 0.8)" element-loading-svg-view-box="0, 0, 50, 50">
      <div class="page_list_item p_18" v-for="page in pageList" :key="page.project_id">
        <div class="h_100 cursor_point relative w_100">
          <div class="my-list_content h_100">
            <div class="my-list-body h_100 ">
              <div class="my-list-body-img black">
                <el-image :src="page.thumb" class="h_100 w_100" fit="cover" lazy>
                </el-image>
                <div
                  class="my-list-body-edit w_100 h_100 absolute bottom_0 left_0 right_0 top_0 flex align_center justify_center">
                  <div class="my-list-body-edit-btn">
                    <div>
                      <el-button size="small" type="primary" class="btn_edit white cursor_point"
                        @click="goDesign(page)">页面设计
                      </el-button>
                    </div>
                    <div class="btn_edit_icon flex justify_between align_center white">
                      <el-tooltip class="toolTipHover" effect="dark" content="复制页面" placement="bottom" trigger="hover">
                        <i class="iconfont icon-copy_link cursor_point" :key="page.page_id"
                          @click="handleCopyPage(page.page_id)" />
                      </el-tooltip>
                      <el-tooltip class="toolTipHover" effect="dark" content="导出页面" placement="bottom" trigger="hover">
                        <i class="iconfont icon-export cursor_point" :key="page.page_id"
                          @click="handleExportPage(page)"></i>
                      </el-tooltip>
                      <el-tooltip class="toolTipHover" effect="dark" content="复制页面链接" placement="bottom"
                        trigger="hover">
                        <i class="iconfont icon-copy_link cursor_point" :key="page.page_id" @click="handleCopyUrl"></i>
                      </el-tooltip>
                      <el-tooltip class="toolTipHover" effect="dark" content="删除页面" placement="bottom" trigger="hover">
                        <i class="iconfont icon-delete cursor_point" :key="page.page_id"
                          @click="handleDelPage(page.page_id)"></i>
                      </el-tooltip>
                    </div>
                  </div>
                  <div class="my-list-body-edit-icon absolute">
                    <el-tooltip class="toolTipHover" effect="dark" content="发布页面" placement="bottom" trigger="hover">
                      <i class="iconfont icon-publish cursor_point white" :key="page.page_id"
                        @click="handlePublish(page.page_id)"></i>
                    </el-tooltip>
                    <el-tooltip class="toolTipHover" effect="dark" content="预览页面" placement="bottom" trigger="hover">
                      <i class="iconfont icon-preview cursor_point white" :key="page.page_id"
                        @click="handlePreview(page.page_url)"></i>
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </div>
            <div class="my-list-footer px_8 fontsize_14 flex justify_between align_center">
              <div v-if="editFlag && selectId===page.page_id">
                <el-input v-model.trim="page.name" @blur="handleEditPageName(page)" size="small" placeholder="输入名称"
                  @keydown.enter="$event.target.blur()">
                </el-input>
              </div>
              <div v-else>
                {{ page.name }}
                <span class="iconfont icon-edit edit-btn" @click="editPageName(page)"></span>
              </div>
              <div v-if="page.publish === 1">
                <span class="dotted publish"></span>已发布
              </div>
              <div v-else>
                <span class="dotted no-publish"></span>未发布
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-pagination class="mt_16 right" v-model:currentPage="query.size" :page-size="query.limit" :page-sizes="[8,10, 20, 40, 50]"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange"></el-pagination>
    <el-drawer v-model="drawerActive" append-to-body title="新增页面" size="460px" direction="rtl"
      custom-class="page-add_form">
      <div>
        <el-form :model="pageModel" :rules="rules" ref="pageFormRef" label-placement="left" label-align="right"
          :label-width="80" size="small">
          <el-form-item label="名称:" prop="name">
            <el-input placeholder="页面名称" v-model.trim="pageModel.name" />
          </el-form-item>
          <el-form-item label="布局方式:" prop="layout">
            <el-select v-model="pageModel.layout" filterable placeholder="布局方式" class="w_100">
              <el-option label="大屏布局" value="absolute"></el-option>
              <el-option label="栅格化布局" value="grid"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注:" prop="remark">
            <el-input placeholder="备注" v-model.trim="pageModel.remark" type="textarea" :autosize="{
                              minRows: 3,
                              maxRows: 5
                            }" />
          </el-form-item>
          <el-upload class="avatar-uploader" :action="requestUrl" :headers="{Authorization:token}"
            :show-file-list="false" :on-success="handlePicUploadFinish" :before-upload="beforePicUpload">
            <img v-if="pageModel.thumb" :src="pageModel.thumb" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <span class="iconfont icon-Add"></span>
            </el-icon>
          </el-upload>
        </el-form>
        <div class="footer-modal fixed bottom_0 p_8 text_right right_0">
          <el-button type="primary" size="small" class="mx_8" @click="handleAddPageAction">确认
          </el-button>
          <el-button type="info" size="small" @click="drawerActive = false">取消</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref, watch } from "vue";
import { useRouter } from "vue-router";
import {
  addPage,
  deletePage,
  editPage,
  getPageInfoByProjectId,
  publishPage,
} from "../../service/project";
import { getToken } from "../../utils/storage";
import { pageCopyById, readPageInfo } from "../../service/page";
import { saveJSON } from "../../utils/utils";
import { loadingSvg } from "../../utils/constant";

export default defineComponent({
  name: "my-page-list",
  components: {},
  props: {
    project_id: {
      type: Number,
      required: true,
    },
  },
  setup(props, ctx) {
    const query = ref({
      project_id: 0,
      limit: 8,
      size: 1,
    });
    const total = ref(0);
    const router = useRouter();
    const projectInfo = ref({
      name: "",
    });
    const pageModel = ref({
      name: "",
      thumb: "",
      remark: "",
      layout: "",
      project_id: props.project_id,
    });
    const pageFormRef = ref(null);
    const pageLoading = ref(false);
    const formLoading = ref(false);
    const editFlag = ref(false);
    const selectId = ref(null);
    const pageList = ref([]);
    const drawerActive = ref(false);
    const requestUrl = ref();
    const token = ref("");
    const requestData = ref("");
    const resetForm = () => {
      pageModel.value = {
        thumb: "",
        name: "",
        layout: "",
        project_id: props.project_id,
        remark: "",
      };
    };
    watch(
      () => props.project_id,
      (newV, preV) => {
        if (newV) {
          query.value.project_id = props.project_id;
          getPageList();
        }
      }
    );
    const getPageList = () => {
      pageLoading.value = true;
      getPageInfoByProjectId(query.value)
        .then((res) => {
          projectInfo.value = res.data.projectInfo;
          pageList.value = res.data.result;
          total.value = res.data.total;
          pageLoading.value = false;
        })
        .catch((err) => {
          ElMessage.error(err.message);
          pageLoading.value = false;
        });
    };
    const handleSizeChange = (pageSize) => {
      query.value.size = 1;
      query.value.limit = pageSize;
      getPageList();
    };
    const handleCurrentChange = (size) => {
      query.value.size = size;
      getPageList();
    };
    const handleDelPage = (page_id) => {
      ElMessageBox.confirm("你确定删除当前页面?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        pageLoading.value = true;
        deletePage({ page_id })
          .then(() => {
            ElMessage({
              message: "删除页面成功",
              type: "success",
            });
            getPageList();
            ctx.emit("deletepage", props.project_id);
          })
          .catch((err) => {
            ElMessage.error(err.message);
            pageLoading.value = false;
          });
      });
    };
    const handlePublish = (page_id) => {
      ElMessageBox.confirm("你确定发布当前页面", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        pageLoading.value = true;
        publishPage({ page_id })
          .then(() => {
            ElMessage({
              message: "发布页面成功",
              type: "success",
            });
            getPageList();
          })
          .catch((err) => {
            ElMessage.error(err.message);
            pageLoading.value = false;
          });
      });
    };
    const editPageName = (page) => {
      pageModel.value = page;
      selectId.value = page.page_id;
      editFlag.value = true;
    };
    const handleEditPageName = (page) => {
      if (!page.name) {
        ElMessage.error("请输入页面名称");
        return;
      }
      pageLoading.value = true;
      editPage(pageModel.value)
        .then(() => {
          ElMessage({
            message: "修改页面成功",
            type: "success",
          });
          getPageList();
          drawerActive.value = false;
          editFlag.value = false;
        })
        .catch((err) => {
          ElMessage.error(err.message);
          pageLoading.value = false;
        });
    };
    const handleOpenPageDialog = () => {
      resetForm();
      drawerActive.value = true;
    };
    const handleAddPageAction = () => {
      formLoading.value = true;
      pageFormRef.value.validate((valid) => {
        if (valid) {
          addPage(pageModel.value)
            .then((res) => {
              ElMessage({
                message: "新增页面成功",
                type: "success",
              });
              getPageList();
              drawerActive.value = false;
              formLoading.value = false;
            })
            .catch((err) => {
              ElMessage.error(err.message);
              formLoading.value = false;
            });
        }
      });
    };
    const handlePicUploadFinish = (res) => {
      if (res.code === 0) {
        const { path } = res.data;
        pageModel.value.thumb = import.meta.env.VITE_APP_REQUEST + path;
        requestData.value = import.meta.env.VITE_APP_REQUEST + path;
      }
    };
    const beforePicUpload = (file) => {
      if (!["image/jpeg", "image/png", "image/jpg"].includes(file.type)) {
        ElMessage.error("只能上传png/jpg格式的文件，请重新上传");
        return false;
      }
      return true;
    };
    const handlePreview = (id) => {
      let routeData = router.resolve({
        name: "Preview",
        params: { screenId: id },
      });
      window.open(routeData.href, "_blank");
    };
    const handleCopyUrl = (page_url) => {};
    const goDesign = (page) => {
      let designPage = router.resolve({
        path: `/design/${page.page_url}`,
      });
      window.open(designPage.href, "_blank");
    };
    const handleCopyPage = (page_id) => {
      pageLoading.value = false;
      pageCopyById({ page_id })
        .then((res) => {
          ElMessage({
            message: "页面拷贝成功",
            type: "success",
          });
          getPageList();
        })
        .catch(() => {
          pageLoading.value = false;
        });
    };
    const handleExportPage = (page) => {
      pageLoading.value = true;
      readPageInfo({ page_url: page.page_url })
        .then((res) => {
          saveJSON(res.data.result, `${page.name}.json`);
          pageLoading.value = false;
        })
        .catch(() => {
          pageLoading.value = false;
        });
    };
    onMounted(() => {
      query.value.project_id = props.project_id;
      token.value = "Bearer " + getToken();
      requestUrl.value =
        import.meta.env.VITE_APP_REQUEST + "/v1/dataPicture/upload";
      getPageList();
    });
    return {
      total,
      goDesign,
      getPageList,
      handleDelPage,
      handlePublish,
      handlePreview,
      handleCopyUrl,
      handleCopyPage,
      handleSizeChange,
      handleCurrentChange,
      handleExportPage,
      pageLoading,
      formLoading,
      token,
      requestUrl,
      projectInfo,
      pageList,
      query,
      editFlag,
      selectId,
      pageModel,
      pageFormRef,
      requestData,
      handlePicUploadFinish,
      beforePicUpload,
      editPageName,
      handleEditPageName,
      drawerActive,
      handleOpenPageDialog,
      handleAddPageAction,
      loadingSvg: loadingSvg,
      rules: ref({
        name: {
          required: true,
          trigger: ["blur", "input"],
          message: "请输入页面名称",
        },
      }),
    };
  },
});
</script>

<style lang="less" scoped>
@import "page.less";

.avatar-uploader {
  text-align: center;
  margin-top: 24px;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #686565;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 260px;
  height: 178px;
  text-align: center;
  line-height: 170px;
}

.avatar {
  width: 260px;
  height: 178px;
  display: block;
}
</style>
